import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  FlatList,
  Image,
  StyleSheet,
  RefreshControl,
} from 'react-native';
import useHideTabBar from '../utils/useHideTabBar';
import {useNavigation} from '@react-navigation/native';
import theme from '../utils/theme';
import {getData} from '../utils/storageUtils';
import { normalize, screenHeight, stringTofixed } from "../utils/commonUtils";
import API from '../Network/Api';
import { CustomText } from "../customview/CustomText";

const PointsRecordPage = () => {
  const [records, setRecords] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);
  const [totalPoints, setTotalPoints] = useState(0);
  const navigation = useNavigation();
  useHideTabBar(navigation);

  useEffect(() => {
    const getTotalEarningsFromStorage = async () => {
      try {
        const userInfo = await getData('userInfoKey');
        if (userInfo.sumPoints) {
          setTotalPoints(stringTofixed(userInfo.sumPoints));
        }
      } catch (error) {
        console.error('从本地存储获取总收益失败:', error);
      }
    };

    getTotalEarningsFromStorage();
    fetchRecords(1);
  }, []);

  const fetchRecords = async currentPage => {
    try {
      const response = await API.getPointRecordList(currentPage, 20);
      if (response.resultCode === '1') {
        const list = response.data.pointRecord.rows || [];
        const total = response.data.pointRecord.total;
        if (currentPage === 1) {
          setRecords(list);
        } else {
          setRecords(prevRecords => [...prevRecords, ...list]);
        }
        setHasMore(records.length + list.length < total);
      }
    } catch (error) {
      console.error('获取收益记录失败:', error);
    } finally {
      setRefreshing(false);
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    setPage(1);
    await fetchRecords(1);
  };

  const onEndReached = async () => {
    if (hasMore) {
      const nextPage = page + 1;
      setPage(nextPage);
      await fetchRecords(nextPage);
    }
  };

  const renderItem = ({item}) => (
    <View style={styles.recordItem}>
      <View style={styles.itemInfo}>
        <CustomText style={styles.itemDescription}>{item.extendsOne}</CustomText>
        <CustomText style={styles.itemTime}>{item.createTime}</CustomText>
      </View>
      {item.jfbhlx === '1' ? (
        <CustomText style={styles.itemAmount}>+{stringTofixed(item.bhjf)}</CustomText>
      ) : (
        <CustomText style={styles.itemAmount}>-{stringTofixed(item.bhjf)}</CustomText>
      )}
    </View>
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无积分明细</CustomText>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 显示总收益 */}
      <View style={styles.totalEarningsContainer}>
        <CustomText style={styles.totalEarningsTipText}>可使用积分</CustomText>
        <CustomText style={styles.totalEarningsText}>{totalPoints}</CustomText>
      </View>
      {/* 收益记录列表 */}
      <FlatList
        data={records}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        style={styles.recordList}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        ListEmptyComponent={EmptyListComponent}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  totalEarningsContainer: {
    backgroundColor: theme.colors.primary,
    marginTop: 10,
    marginHorizontal: 10,
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 2,
  },
  totalEarningsTipText: {
    fontSize: normalize(16),
    color: '#fff',
    marginTop: 20,
    marginLeft: 15,
  },
  totalEarningsText: {
    fontSize: normalize(24),
    color: '#fff',
    marginTop: 20,
    marginBottom: 20,
    marginLeft: 15,
  },
  recordList: {
    padding: 10,
  },
  recordItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 10,
    marginBottom: 10,
    borderRadius: 8,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 2,
    elevation: 2,
  },
  itemImage: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 15,
  },
  itemInfo: {
    flex: 1,
  },
  itemDescription: {
    fontSize: normalize(14),
    color: '#333',
  },
  itemTime: {
    fontSize: normalize(12),
    color: '#999',
    marginTop: 5,
  },
  itemAmount: {
    fontSize: normalize(15),
    color: '#FF6B6B',
  },
  itemAmount1: {
    fontSize: normalize(15),
    color: '#000',
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    flex: 1,
    fontSize: normalize(16),
    color: '#999',
  },
});

export default PointsRecordPage;
